<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
        <n-form-item label="姓名" path="name">
          <n-input v-model:value="formValue.name" placeholder="请输入姓名" />
        </n-form-item>

        <n-form-item label="手机号码(用于登录)" path="mobile">
          <n-input placeholder="请输入手机号码" v-model:value="formValue.mobile" />
        </n-form-item>

        <n-form-item label="密码(不填不做修改)" path="password">
          <n-input v-model:value="formValue.password" type="password" placeholder="请输入密码" />
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit">更新基本信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { ResultEnum } from '@/enums/httpEnum';
  import { getAdmin, patchAuth } from '@/api/admin/admin';
  import { useUser } from '@/store/modules/user';

  const rules = {
    name: {
      required: true,
      message: '请输入姓名',
      trigger: 'blur',
    },
    mobile: {
      required: true,
      message: '请输入联系电话',
      trigger: 'input',
    },
  };
  const formRef: any = ref(null);
  const message = useMessage();

  const formValue = reactive({
    name: '',
    mobile: '',
    password: '',
  });

  function formSubmit() {
    formRef.value.validate(async (errors) => {
      if (!errors) {
        const phoneRegExp = /^1[3-9]\d{9}$/;
        if (!phoneRegExp.test(formValue.mobile)) {
          message.error('手机号码格式错误');
          return;
        }
        const response: any = await patchAuth(formValue);
        if (response.code == ResultEnum.SUCCESS) {
          message.success('更新成功');
        }
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  const getData = async () => {
    const userStore = useUser();
    const userInfo = userStore.getUserInfo;
    const response: any = await getAdmin(userInfo.id);
    if (response.code === ResultEnum.SUCCESS) {
      let obj: any = {
        name: response.data.name,
        mobile: response.data.mobile,
        password: '',
      };
      Object.assign(formValue, obj);
    }
  };

  onMounted(() => {
    getData();
  });
</script>
